/***
 * newsController
 */
const _ = require('lodash')
const { nanoid } = require('nanoid')
const globalSendResult = require('../utils/globalSendResult')
const NewsServices = require('../services/NewsServices')
const dateFormat = require('../utils/date')
const NewsController = {
    add: (req,res) => {
        console.log(req.body)
        // 复制一份儿数据
        const newsData = _.clone(req.body)
        // 处理封面图片
        const cover = (req.file && typeof req.file !== 'string') ? `/images/covers/${req.file.filename}` : null
        const formatData = {
            newsid: nanoid(),
            publishdate: dateFormat(),
            cover,
        }
        globalSendResult({
            promiseFunc: NewsServices.add(Object.assign(newsData,formatData)),
            response: res,
            errMsg: '新增失败',
            msg: '新增',
            isReturn: false
        })
    },
    edit: (req,res) => {
        const editData = _.clone(req.body)
        const cover = req.file ? `/images/covers/${req.file.filename}` : null
        globalSendResult({
            promiseFunc: NewsServices.edit(Object.assign(editData, cover ? { cover, publishdate: dateFormat() } : {})),
            response: res,
            errMsg: '修改失败',
            msg: '修改',
            isReturn: false
        })
    },
    query: (req,res) => {
        const { limit = 12, page = 1, title, status } = req.query
        const queryData = {
            limit: Number(limit) || 12,
            page,
            title
        }
        if(status) queryData.status = status
        globalSendResult({
            promiseFunc: NewsServices.query(queryData),
            response: res,
            errMsg: '查询失败',
            msg: '查询',
            countTotal: true,
            queryData,
            Services: NewsServices,
        })
    },
    deleteOne: (req,res) => {
        const { newsid }  = req.body
        globalSendResult({
            promiseFunc: NewsServices.deleteOne(newsid),
            response: res,
            errMsg: '删除失败',
            msg: '删除',
            isReturn: false
        })
    },
    queryOne: (req,res) => {
        const { newsid }  = req.query
        globalSendResult({
            promiseFunc: NewsServices.queryOne(newsid),
            response: res,
            errMsg: '查询失败',
            msg: '查询',
        })
    }
}

module.exports = NewsController
